// admin/system/dao/sys_dict_type_dao.go
package dao

import (
	"go-admin1/admin/system/model"
	"go-admin1/internal/infrastructure/database"
	"go-admin1/internal/infrastructure/logger"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

// SysDictTypeDao 字典类型数据访问接口
type SysDictTypeDao interface {
	Create(dictType *model.SysDictType) error
	GetByID(id int64) (*model.SysDictType, error)
	GetByDictType(dictType string) (*model.SysDictType, error)
	Update(dictType *model.SysDictType) error
	Delete(id int64) error
	List(page, pageSize int) ([]*model.SysDictType, int64, error)
	ListAll() ([]*model.SysDictType, error)
}

type sysDictTypeDao struct {
	db *gorm.DB
}

// NewSysDictTypeDao 创建字典类型数据访问实例
func NewSysDictTypeDao() SysDictTypeDao {
	return &sysDictTypeDao{
		db: database.GetDB(),
	}
}

func (d *sysDictTypeDao) Create(dictType *model.SysDictType) error {
	logger.Info("创建字典类型", zap.Int64("dict_id", dictType.DictID))
	return d.db.Create(dictType).Error
}

func (d *sysDictTypeDao) GetByID(id int64) (*model.SysDictType, error) {
	logger.Debug("根据ID获取字典类型", zap.Int64("dict_id", id))
	var dictType model.SysDictType
	err := d.db.Where("dict_id = ? AND status = '0'", id).First(&dictType).Error
	return &dictType, err
}

func (d *sysDictTypeDao) GetByDictType(dictType string) (*model.SysDictType, error) {
	logger.Debug("根据字典类型获取字典类型", zap.String("dict_type", dictType))
	var dict model.SysDictType
	err := d.db.Where("dict_type = ? AND status = '0'", dictType).First(&dict).Error
	return &dict, err
}

func (d *sysDictTypeDao) Update(dictType *model.SysDictType) error {
	logger.Info("更新字典类型", zap.Int64("dict_id", dictType.DictID))
	return d.db.Save(dictType).Error
}

func (d *sysDictTypeDao) Delete(id int64) error {
	logger.Info("删除字典类型", zap.Int64("dict_id", id))
	return d.db.Where("dict_id = ?", id).Delete(&model.SysDictType{}).Error
}

func (d *sysDictTypeDao) List(page, pageSize int) ([]*model.SysDictType, int64, error) {
	logger.Debug("获取字典类型列表", zap.Int("page", page), zap.Int("page_size", pageSize))
	var dictTypes []*model.SysDictType
	var total int64

	offset := (page - 1) * pageSize
	db := d.db.Model(&model.SysDictType{}).Where("status = '0'")

	if err := db.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if err := db.Offset(offset).Limit(pageSize).Find(&dictTypes).Error; err != nil {
		return nil, 0, err
	}

	return dictTypes, total, nil
}

func (d *sysDictTypeDao) ListAll() ([]*model.SysDictType, error) {
	logger.Debug("获取所有字典类型列表")
	var dictTypes []*model.SysDictType
	err := d.db.Where("status = '0'").Find(&dictTypes).Error
	return dictTypes, err
}
